Java处理时间加减天数加减月

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**** 
* 传入具体日期 ,返回具体日期增加一个月。
* @param date 日期(2017-04-13)
* @return 2017-05-13
* @throws ParseException
*/
private String calculateMonth(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt = sdf.parse(date);
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(dt);
rightNow.add(Calendar.MONTH, 1);
Date dt1 = rightNow.getTime();
String reStr = sdf.format(dt1);
return reStr;
}


/****
* 传入具体日期 ,返回具体日期减少一天
* @param date 日期(2017-04-13)
* @return 2017-04-12
* @throws ParseException
*/
private String calculateDay(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt = sdf.parse(date);
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(dt);
rightNow.add(Calendar.DATE, -1);
Date dt1 = rightNow.getTime();
String reStr = sdf.format(dt1);
return reStr;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 传入具体日期 ,返回具体日期增加或者减少天数,传出日期
* @author wjk
* @Date 2021-09-27
*/
private Date calculateDay(Date date,int day){
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.add(Calendar.DATE, day);
Date date1 = rightNow.getTime();
return date1;
}


/**
* 传入具体日期 ,返回具体日期增加或者减少月数,传出日期
* @author wjk
* @Date 2021-09-27
*/
private Date calculateMonth(Date date,int month){
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(date);
rightNow.add(Calendar.MONTH, month);
Date date1 = rightNow.getTime();
return date1;
}
1
2
3
4
5
6
7
8
9
10
/**
* 传入具体日期 ,返回当月的天数
* @author wjk
* @Date 2021-09-28
*/
public static int getDaysOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 获取当月最后几天
* @param days
* @return
*/
private static List<String> getLastDays(int days) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
List<String> list=new ArrayList<String>();
for(int i=1;i<=days;i++){
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, 1);
calendar.add(Calendar.DATE, -i);
Date theDate = calendar.getTime();
String s = df.format(theDate);
list.add(s);
}
return list;
}}
继开 wechat
欢迎加我的微信,共同交流技术